#include "my_pthread.h"
#include "stdio.h"
#include "shm.h"
#include "common.h"
#include <sys/time.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include "cJSON.h"

MsgQueue queue;
MQTTClient pub_client;
MQTTClient sub_client;
void* shm_addr = NULL;
int g_quit = 0;

MsgQueue tcp_msg_queue;//初始化TCP消息队列

static int parse_tcp_msg(const char* tcp_msg, devdata* data) 
{
    // 解析TCP消息为devdata结构体（格式："tem:%lf,hum:%lf"）
    int ret = sscanf(tcp_msg, "id:%d,tem:%lf,hum:%lf",
    &data->dev_id,&data->tem, &data->hum);
    if (ret != 3) 
    {
        printf("[parse_tcp_msg] 消息格式错误: %s\n", tcp_msg);
        return -1;
    }
    // 补充时间戳
    //data->timestamp = time(NULL);
    return 0;
}

void* tcp_to_shm_thread(void* arg) 
{
    msg_queue_init(&tcp_msg_queue); //初始化TCP消息队列
    printf("[tcp_to_shm_thread] 线程启动，等待TCP消息...\n");

    while (!g_quit) 
    {
        // 从队列阻塞读取TCP消息
        char* tcp_msg = msg_queue_read(&tcp_msg_queue);
        if (!tcp_msg) 
        {
            continue;  // 队列退出时返回NULL
        }
        //解析消息为共享内存数据结构
        devdata shm_data;
        if (parse_tcp_msg(tcp_msg, &shm_data) != 0) 
        {
            free(tcp_msg);
            continue;
        }
        //将devdata序列化为JSON字符串
         cJSON* json = cJSON_CreateObject();  // 创建JSON
        if(!json) 
        {
            printf("[tcp_to_shm_thread] JSON创建失败\n");
            free(tcp_msg);
            continue;
        }
        cJSON_AddNumberToObject(json, "dev_id", shm_data.dev_id);
        cJSON_AddNumberToObject(json, "tem", shm_data.tem);
        cJSON_AddNumberToObject(json, "hum", shm_data.hum);
        //cJSON_AddNumberToObject(json, "status", shm_data.status);
        //cJSON_AddNumberToObject(json, "timestamp", shm_data.timestamp);
        
        // 转换为JSON字符串（无格式压缩）
        char* json_str = cJSON_PrintUnformatted(json);
        if(!json_str) 
        {
            printf("[tcp_to_shm_thread] JSON序列化失败\n");
            cJSON_Delete(json);
            free(tcp_msg);
            continue;
        }

        //写入共享内存
        if(shm_write_data(shm_addr, json_str)!= 0) 
        {
            printf("[tcp_to_shm_thread] 共享内存写入失败\n");
        } 
        else 
        {
            printf("[tcp_to_shm_thread] 写入共享内存成功:%s/n", json_str);

            char read_buf[SHM_SIZE];
            memcpy(read_buf,shm_addr,SHM_SIZE);
            printf("[验证]共享内存实际内柔：%s\n",read_buf);
        }

        cJSON_Delete(json);//释放JSON对象
        free(json_str);//释放JSON字符串
        free(tcp_msg);//释放消息内存
    }
    msg_queue_destory(&tcp_msg_queue); //销毁队列
    printf("[tcp_to_shm_thread] 线程退出\n");
    return NULL;
}

// 统一创建所有线程（对外接口）
int create_all_threads(pthread_t* t1) 
{
    if (pthread_create(t1, NULL, tcp_to_shm_thread, NULL) != 0) 
    {
        printf("[create_all_threads] 创建tcp_to_shm_thread失败\n");
        return -1;
    }

    return 0;
}


